<template>
  <div>
    <div ref="chartContainer" :style="style" class="chart-container"></div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick, watch, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
const chartContainer = ref(null);// 示例数据
let myChart;
let resizeObserver;
const props = defineProps({
  //子组件接收父组件传递过来的值
  option: Object,
  style: Object
})
//使用父组件传递过来的值
const { option } = toRefs(props);
function initChart() {
  try {
    // 确保 DOM 已加载
    const chartDom = chartContainer.value;
    
    if (chartDom) {
      myChart = echarts.init(chartDom,null,{ renderer : 'svg' });
      // 设置配置项
      myChart.setOption(option.value);
      setupResizeObserver();
      nextTick(() => {
        myChart?.resize();
      });
      window.addEventListener('resize', handleWindowResize);
    }
  } catch (error) {
    console.log(error);
  }
}
const destroyChart = () => {
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
  }
  window.removeEventListener('resize', handleWindowResize);
}
watch(option, () => {
  console.log(option);
  
  destroyChart();
  initChart();
});
// 初始化图表
onMounted(() => {
  nextTick(() => {
    initChart();
  })
});

const setupResizeObserver = () => {
  if (!chartContainer.value || typeof ResizeObserver === 'undefined') return;
  if (resizeObserver) resizeObserver.disconnect();
  resizeObserver = new ResizeObserver(() => {
    nextTick(() => {
      myChart?.resize();
    })
  });
  resizeObserver.observe(chartContainer.value);
}

const handleWindowResize = () => {
  myChart?.resize();
}

onBeforeUnmount(() => {
  destroyChart();
});
</script> 

<style>
.chart-container {
  width: 100%;
  height: 350px;
}
</style>